package com.gvsoft.thread;

import com.gvsoft.Client;
import com.gvsoft.analyse.AnalyseTools;
import com.gvsoft.analyse.inf.IServerPacket;
import com.gvsoft.analyse.order.ClientLoginOrder;
import com.gvsoft.analyse.order.ClientOrder;
import com.gvsoft.analyse.order.ClientReplyOrder;
import com.gvsoft.analyse.packet.ServerMsgPacket;
import com.gvsoft.analyse.packet.ServerReplyPacket;
import com.gvsoft.analyse.packet.ServerTokenPacket;
import com.gvsoft.busi.MsgInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgClient
 * Author: zhaoqiubo
 * Date: 15/8/1
 * Time: 下午3:11
 * Desc: 通讯报文消费者线程，专门对服务端发送过来的报文。
 */

public class PacketConsumer extends Thread {

    private static Logger logger = LogManager.getLogger(PacketConsumer.class.getName());

//    private static KeepChannelThread keepChannelThread = new KeepChannelThread();

    public void run() {

        logger.info( "通讯报文消费者线程启动……");
        boolean isRunning = true;
        try {
            while (isRunning) {
                String msgFromServer = (String) Client.MSGQUEUE.poll(1, TimeUnit.SECONDS);
                if (msgFromServer != null) {
                    try {
                        IServerPacket sp = AnalyseTools.analyseServerPacket(msgFromServer);
                        if (sp == null || Client.getPacketInstance(sp.getHeader()) == null) {
                            logger.info( "收到服务端非法报文：" + msgFromServer);
                            continue;

                        } else {
                            logger.info("收到服务端报文："+msgFromServer);
                            handleServerPacket(sp);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                } else {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    Logs.info("【PacketConsumer】", "消息队列中没有消息，休息一会儿……");
                }
            }
        } catch (InterruptedException e) {
            logger.info( "消息队列处理线程终止……");
            e.printStackTrace();
        }
    }

    /**
     * 处理
     *
     * @param sp
     */
    private void handleServerPacket(IServerPacket sp) {
        /**
         * 处理从服务端收到的T报文
         */
        if (sp.getHeader().equals(ServerTokenPacket.HEADER)) {

            //设置指令实例的token
            for (Map.Entry<String, Object> entry : Client.getOrderMap().entrySet()) {
                ((ClientOrder) entry.getValue()).setToken(sp.getToken());
            }
            Client.KEEP_ORDER_MAP.clear();

            //返回R响应
            ClientReplyOrder clientReplyOrder = (ClientReplyOrder) Client.getOrderInstance(ClientReplyOrder.HEADER);
            clientReplyOrder.initClientReplyOrder(sp.getRid());
            try {
                Client.write2Channel(clientReplyOrder);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //发送用户登录报文
            ClientLoginOrder clientLoginOrder = (ClientLoginOrder) Client.getOrderInstance(ClientLoginOrder.HEADER);
            clientLoginOrder.initClientLoginOrder();
            try {
                Client.write2Channel(clientLoginOrder);
            }catch (IOException e){
                e.printStackTrace();
            }
//            //启动维持链路线程
//            if (!keepChannelThread.isAlive()){
//                keepChannelThread.start();
//                logger.info("维持链路线程启动……");
//            }
        }
        /**
         * 处理从服务端收到的R报文
         */
        if(sp.getHeader().equals(ServerReplyPacket.HEADER)){
            //清除维持链路报文缓冲区
            if(Client.KEEP_ORDER_MAP.containsKey(sp.getRid())) {
                Client.KEEP_ORDER_MAP.clear();
                logger.info( "清除维护链路指令缓存Map！");
            }
        }

        if(sp.getHeader().equals(ServerMsgPacket.HEADER)){

            MsgInfo msgInfo = new MsgInfo();
            msgInfo = msgInfo.generaterMsgInfo(sp.getBody());
            MsgInfo.MQUEUE.offer(msgInfo);
            if (logger.isDebugEnabled()) {
                logger.debug("将短消息放入短消息消费队列：" + sp.getBody());
            }
        }
    }
}
